package etnorservice.etnor_service.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/02/28/14:48
 **/
@Slf4j
@Component
public class ApiTokenUtil {
//    @Value("${token.secret:your-secret-key}")
    private String secret="ETNORAPISECURITYETNORAPISECURITYETNORAPISECURITYETNORAPISECURITYETNORAPISECURITYETNORAPISECURITY";

//    @Value("${token.expiration:3600}")
    private long expiration=3600; // 默认1小时过期

    /**
     * 生成token
     * @param userId 用户ID
     * @param apiId 接口ID
     * @return token字符串
     */
    public String generateToken(Long userId, String apiId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("apiId", apiId);
        claims.put("created", new Date());

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取用户ID
     * @param token token字符串
     * @return 用户ID
     */
    public Long getUserIdFromToken(String token) throws Exception {
        try {
            Claims claims = getClaimsFromToken(token);
            return Long.valueOf(claims.get("userId").toString());
        } catch (Exception e) {
            log.error("从token获取用户ID失败", e);
            return null;
        }
    }

    /**
     * 从token中获取接口ID
     * @param token token字符串
     * @return 接口ID
     */
    public Long getApiIdFromToken(String token) throws Exception {
        try {
            Claims claims = getClaimsFromToken(token);
            return Long.valueOf(claims.get("apiId").toString());
        } catch (Exception e) {
            log.error("从token获取接口ID失败", e);
            return null;
        }
    }

    /**
     * 验证token是否有效
     * @param token token字符串
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return !expiration.before(new Date());
        } catch (ExpiredJwtException e) {
            log.error("Token已过期", e);
            return false;
        } catch (Exception e) {
            log.error("Token验证失败", e);
            return false;
        }
    }

    /**
     * 验证token是否匹配指定的用户ID和接口ID
     * @param token token字符串
     * @param userId 用户ID
     * @param apiId 接口ID
     * @return 是否匹配
     */
    public boolean validateToken(String token, Long userId, Long apiId) {
        try {
            Claims claims = getClaimsFromToken(token);
            Long tokenUserId = Long.valueOf(claims.get("userId").toString());
            Long tokenApiId = Long.valueOf(claims.get("apiId").toString());
            Date expiration = claims.getExpiration();

            return tokenUserId.equals(userId) &&
                    tokenApiId.equals(apiId) &&
                    !expiration.before(new Date());
        } catch (Exception e) {
            log.error("Token验证失败", e);
            return false;
        }
    }

    /**
     * 从token中获取Claims
     * @param token token字符串
     * @return Claims对象
     */
    private Claims getClaimsFromToken(String token) throws Exception {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取token的剩余有效期（秒）
     * @param token token字符串
     * @return 剩余有效期，token无效则返回-1
     */
    public long getTokenRemainingTime(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return (expiration.getTime() - System.currentTimeMillis()) / 1000;
        } catch (Exception e) {
            return -1;
        }
    }
}



